package com.yyfax.pay.common.filter;

import java.util.Iterator;

import javax.annotation.PostConstruct;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.yyfax.framework.mq.MQConfigure;

/**
 * mock服务配置
 */
@Component
public class MockConfigure {
	
	private boolean mockSwitch = false;
	
	@Value("#{globalProp[mockSwitch]}") 
	public void setMockSwitch(String mockSwitch) {
		if(null != mockSwitch){
			this.mockSwitch = mockSwitch.toUpperCase().equals("ON") ? true : false;
		}
	}
	
	public boolean isMock() {
		return mockSwitch;
	}

	private  Logger logger = LoggerFactory.getLogger(MQConfigure.class);

	protected  Multimap<String,MockConfigure> configures = ArrayListMultimap.create(); 
	
	public Multimap<String, MockConfigure> getConfigures() {
		return configures;
	}

	@PostConstruct
	private void init(){
		// 自动检测quartz.properties文件,并导入配置.
		try {
			if(!mockSwitch){
				return;
			}
			PropertiesConfiguration c = new PropertiesConfiguration(); // classpath目录
			c.setDelimiterParsingDisabled(true);
			c.setFileName("mock.properties");
			c.load();
			if (c != null) {
				Iterator<String> keys = c.getKeys();
				String key;
				while (keys.hasNext()) {
					key = keys.next();
					if (configures.containsKey(key) || !StringUtils.endsWith(key, "url.reg")) {
						continue;
					}
					key = key.substring(0, key.length() - 8);
					String url = null;
					String reg = null;
					String response = null;
					url = c.getString(key.concat(".url.reg"));
					if (StringUtils.isEmpty(c.getString(key.concat(".param.reg")))) {
						throw new Exception(key.concat(".param.reg") + "配置错误");
					}
					reg = c.getString(key.concat(".param.reg"));
					if (StringUtils.isEmpty(c.getString(key.concat(".response")))) {
						throw new Exception(key.concat(".response") + "配置错误");
					}
					response = c.getString(key.concat(".response"));
					configures.put(url, new MockConfigure(url, reg, response));
					logger.info("初始化mock: {}", configures.get(key));

				}
			}
		} catch (ConfigurationException e) {
			logger.warn("配置{}不存在 ", "mock.properties");
			// e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private  String url;

	private  String reg;

	private  String response;
	
	public MockConfigure(){
		
	}

	public MockConfigure(String url, String reg, String response) {
		this.url = url;
		this.reg = reg;
		this.response = response;
	}

	public String getResponse() {
		return response;
	}

	public String getUrl() {
		return url;
	}

	public String getReg() {
		return reg;
	}
}